﻿namespace CodingExercises._41_50;

public class BinarySearch
{
    // 二分查找
    public static int Method(int[] numbers, int target)
    {
        if (numbers is null)
        {
            throw new ArgumentNullException();
        }

        int left = 0;
        int right = numbers.Length - 1;
        while (left <= right)
        {
            int mid = (left + right) / 2;
            if (numbers[mid] == target)
            {
                return mid;
            }
            else if (numbers[mid] < target)
            {
                left = mid + 1;
            }
            else
            {
                right = mid - 1;
            }
        }

        return -1;
    }
}